package cn.edu.heuet.bnve;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.widget.imageview.RadiusImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.edu.heuet.bnve.activity.WebActivity;
import cn.edu.heuet.bnve.fragment.HomeFragment;
import cn.edu.heuet.bnve.fragment.ScheduleFragment;
import cn.edu.heuet.bnve.fragment.SettingFragment;
import cn.edu.heuet.bnve.fragment.TableFragment;
import cn.edu.heuet.bnve.fragment.TodoFragment;
import cn.edu.heuet.bnve.activity.ScheduleActivity.NewHomeworkActivity;
import cn.edu.heuet.bnve.activity.ScheduleActivity.NewScheduleActivity;
import cn.edu.heuet.bnve.activity.SettingActivity.AboutActivity;
import cn.edu.heuet.bnve.activity.SettingActivity.InforSettingActivity;
import cn.edu.heuet.bnve.base.activity.BaseActivity;
import cn.edu.heuet.bnve.databinding.ActivityMainBinding;
import cn.edu.heuet.bnve.databinding.IncludeNavHeaderBinding;
import cn.edu.heuet.bnve.remind.AlarmAlertBroadcastReceiver;
import cn.edu.heuet.bnve.remind.AlarmServiceBroadcastReceiver;
import cn.edu.heuet.bnve.remind.SendAlarmBroadcast;
import cn.edu.heuet.bnve.utils.SharepreferencesUtilSystemSettings;
import cn.edu.heuet.bnve.view.floatButton.FloatingActionButton;
import cn.edu.heuet.bnve.view.floatButton.FloatingActionsMenu;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private String AlarmAlertBroadcastreceiver = "AlarmAlertBroadcastreceiver";
    private String AlarmServiceBroadcastreceiver = "AlarmServiceBroadcastreceiver";

    private static final String TAG = MainActivity.class.getSimpleName();
    public ActivityMainBinding bind;
    private VpAdapter adapter;

    private  Toolbar toolbar;

    FloatingActionsMenu fab;
    View view ;
    RelativeLayout content;
    public  DrawerLayout drawerLayout;
    NavigationView navView;

    private boolean mExpanded = false;

    public FloatingActionsMenu getFab() {
        return fab;
    }

    // collections
    private List<Fragment> fragments;// used for ViewPager adapter

    /**
     * create fragments
     */
    public void initData() {
        //注册广播
        // 从Android9.0开始，系统不再支持静态广播，应用广播只能通过动态注册
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建一个闹钟的广播接收器
            AlarmAlertBroadcastReceiver alarmAlertBroadcastReceiver = new AlarmAlertBroadcastReceiver();
            // 创建一个意图过滤器，只处理指定事件来源的广播
            IntentFilter filter = new IntentFilter(AlarmAlertBroadcastreceiver);
            // 注册广播接收器，注册之后才能正常接收广播
            registerReceiver(alarmAlertBroadcastReceiver, filter);

            AlarmServiceBroadcastReceiver alarmServiceBroadcastReceiver = new AlarmServiceBroadcastReceiver();
            // 创建一个意图过滤器，只处理指定事件来源的广播
            IntentFilter filter1 = new IntentFilter(AlarmServiceBroadcastreceiver);
            // 注册广播接收器，注册之后才能正常接收广播
            registerReceiver(alarmServiceBroadcastReceiver, filter1);
        }
        //通知第一条
        SendAlarmBroadcast.startAlarmService(MainActivity.this);
        fragments = new ArrayList<>(4);

//        // create music fragment and add it
//        BaseFragment musicFragment = new BaseFragment();
//        Bundle bundle = new Bundle();
//        bundle.putString("title", getString(R.string.music));
//        musicFragment.setArguments(bundle);

        HomeFragment homeFragment = new HomeFragment();
        ScheduleFragment scheduleFragment = new ScheduleFragment();
        TodoFragment todoFragment = new TodoFragment();
        TableFragment tableFragment = new TableFragment();
        SettingFragment settingFragment = new SettingFragment();

        // add to fragments for adapter
        fragments.add(homeFragment);
        fragments.add(todoFragment);
        fragments.add(tableFragment);
        fragments.add(settingFragment);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    /**
     * change BottomNavigationViewEx style
     */
    public void initView() {
        XUI.initTheme(this);
        bind = DataBindingUtil.setContentView(this, R.layout.activity_main);
        bind.bnve.enableItemShiftingMode(false);
        bind.bnve.enableShiftingMode(false);
        bind.bnve.enableAnimation(false);

        drawerLayout = bind.drawerLayout;
        navView = bind.navView;
        navView.setItemIconTintList(null);

        // set adapter
        adapter = new VpAdapter(getSupportFragmentManager(), fragments);
        bind.vp.setAdapter(adapter);

        toolbar=bind.toolbarContainer.toolbar;
        setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.home);
        toolbar.setVisibility(View.GONE);

        //改变fab的位置使其居中
        fab = bind.fab;
        WindowManager wm = (WindowManager) this.getSystemService(MainActivity.this.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels; // 屏幕宽度(像素)
        int height = dm.heightPixels;
        int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        fab.measure(w, h);
        int fabWidth =fab.getMeasuredWidth();
        Log.i("wqs",width+" "+height);
        RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        int p = width/2-fabWidth+width*2/25;
        layoutParams.setMargins(p, height*61/100, 0, 0);
        fab.setLayoutParams(layoutParams);

        view = bind.view;
        view.setVisibility(View.GONE);
        view.getBackground().setAlpha(150);

        content = bind.content;



    }

    private void initDrawer() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        initHeadView();
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                initHeadView();

            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });


        navView.setNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()) {

                case R.id.nav_home:
                    bind.bnve.setCurrentItem(0);
                    drawerLayout.close();
                    break;
                case R.id.nav_todo:
                    bind.bnve.setCurrentItem(1);
                    drawerLayout.close();
                    break;
                case R.id.nav_table:
                    bind.bnve.setCurrentItem(3);
                    drawerLayout.close();
                    break;
                case R.id.nav_settings:
                    bind.bnve.setCurrentItem(4);
                    drawerLayout.close();
                    break;
                case R.id.nav_about:
                    AboutActivity.show(this);
                    drawerLayout.close();
                    break;
            }
            return true;
        });

        View headerView = navView.getHeaderView(0);
        LinearLayout navHeader = headerView.findViewById(R.id.nav_header);
        navHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InforSettingActivity.show(MainActivity.this);
                drawerLayout.close();
            }
        });

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });
    }

    /**
     * set listeners
     */
    public  void initEvent() {
        // set listener to change the current item of view pager when click bottom nav item
        bind.bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            private int previousPosition = -1;

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int position = 0;
                switch (item.getItemId()) {
                    case R.id.i_home:
                        toolbar.setTitle(R.string.home);
                        toolbar.setVisibility(View.GONE);
//                        toolbar.setSubtitle(getDate());
                        position = 0;
                        break;
                    case R.id.i_todo:
                        toolbar.setVisibility(View.GONE);
                        toolbar.setTitle(R.string.todo);
                        position = 1;
                        break;
                    case R.id.i_table:
                        toolbar.setVisibility(View.GONE);
                        toolbar.setTitle(R.string.table);
                        position = 2;
                        break;
                    case R.id.i_setting:
                        toolbar.setVisibility(View.VISIBLE);
                        toolbar.setTitle(R.string.setting);
                        position = 3;
                        break;
                    case R.id.i_empty: {
                        return false;
                    }
                }
                if(previousPosition != position) {
                    bind.vp.setCurrentItem(position, false);
                    previousPosition = position;
                    fragments.get(position).onStart();
                }

                return true;
            }
        });

        // set listener to change the current checked item of bottom nav when scroll view pager
        bind.vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position >= 2)// 2 is center
                    position++;// if page is 2, need set bottom item to 3, and the same to 3 -> 4
                bind.bnve.setCurrentItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        fab.mAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        final FloatingActionButton actionA = fab.findViewById(R.id.action_add_schedule);
        actionA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewScheduleActivity.show(MainActivity.this);
                toggle();
            }
        });

        final FloatingActionButton actionB = fab.findViewById(R.id.action_add_homework);
        actionB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewHomeworkActivity.show(MainActivity.this);
                toggle();
            }
        });

        initDrawer();

    }

    @Override
    public void onClick(View view) {

    }

    /**
     * view pager adapter
     */
    private static class VpAdapter extends FragmentPagerAdapter {
        private List<Fragment> data;

        public VpAdapter(FragmentManager fm, List<Fragment> data) {
            super(fm);
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Fragment getItem(int position) {
            return data.get(position);
        }
    }


    public void  toggle() {
        if (mExpanded) {
            fab.collapse();
            mExpanded=false;
            view.setVisibility(View.GONE);
        } else {
            fab.expand();
            mExpanded=true;
            view.setVisibility(View.VISIBLE);
        }
    }

    private  void initHeadView() {
        View headerView = navView.getHeaderView(0);
        IncludeNavHeaderBinding binding = DataBindingUtil.bind(headerView);
        RadiusImageView headImg = binding.ivAvatar;
        String headURI = SharepreferencesUtilSystemSettings.getValue(MainActivity.this, "infor_head", null);
        if (headURI != null) {
            headImg.setImageURI(Uri.fromFile(new File(headURI)));
        }
        String name = SharepreferencesUtilSystemSettings.getValue(MainActivity.this, "infor_name", "无");
        binding.tvAvatar.setText(name);
    }


    @Override
    protected void onStart() {
        super.onStart();

    }
}
